/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        return dfs(root, 0);
    }
    int dfs(TreeNode* root, int x)
    {
        x = x * 10 + root->val;
        int left = 0, right = 0;
        if (root->right == nullptr && root->left == nullptr) return x;
        if (root->left) left = dfs(root->left, x);
        if (root->right) right = dfs(root->right, x);
        return left + right;
    }
};




/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* pruneTree(TreeNode* root) {
        return delete0(root) == false ? nullptr : root;
    }
    bool delete0(TreeNode* root)
    {
        bool r = root->val == 0 ? false : true;
        bool flagl = false, flagr = false;
        if (root->left == nullptr && root->right == nullptr) return r;
        if (root->right) flagr = delete0(root->right);
        if (root->left) flagl = delete0(root->left);
        if (flagr == false) root->right = nullptr;
        if (flagl == false) root->left = nullptr;
        return flagl || flagr || r;
    }
};





































